<template>
  <div class="p-5">
    <el-card shadow="hover" body-class="rounded-lg" class="overflow-y-auto">
      <div class="space-y-4">
        <DateFilter ref="dateRef" @date-change="handleDateChange" @tab-change="handleTabChange" />

        <SolarCard ref="solarRef" :timeType="timeType" :timeScope="currentTimeScope" :dataType="currentDataType" :processedData="processedData" :energyTotals="energyTotals" :isLoading="energyLoading" />

        <HomeCard ref="homeRef" :timeType="timeType" :timeScope="currentTimeScope" :dataType="currentDataType" :processedData="processedData" :energyTotals="energyTotals" :isLoading="energyLoading" />

        <BatteryCard ref="batteryRef" :timeType="timeType" :timeScope="currentTimeScope" :dataType="currentDataType" :processedData="processedData" :energyTotals="energyTotals" :isLoading="energyLoading" />

        <SOCCard :processedData="processedData" :isLoading="energyLoading" />

        <GridCard :timeScope="currentTimeScope" :dataType="currentDataType" :processedData="processedData" :energyTotals="energyTotals" :isLoading="energyLoading" />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, ref, watch } from "vue";
import { energyAppApi } from "@/api/business";
import { BatteryCard, DateFilter, GridCard, HomeCard, SolarCard, SOCCard } from "./components";
import { useEnergyData, type QueryData } from "./hooks/useEnergyData";
import dayjs from "dayjs";

// 使用能源数据hook
const { isLoading, isNothing, energyTotals, processedData, getSolarFlowData, getBatteryData, resetData, aggregate5MinData, formatterArrayData, formatterDate, getGridData } = useEnergyData();

const systemId = ref("");
const energyLoading = ref(false);
const timeType = ref<number>(0);
const solarRef = ref<any>(null);
const homeRef = ref<any>(null);
const dateRef = ref<any>(null);
const batteryRef = ref<any>(null);
const queryData = ref<QueryData | null>(null);

const props = defineProps({
  systemId: {
    type: String,
    required: true
  }
});
systemId.value = props.systemId;
let currentSelectTime = null as any;
// console.log("systemId====>",props)
onMounted(() => {
  nextTick(() => {
    currentSelectTime = formatDate(dateRef.value.selectedDate); //"2025-09-03"
    if (systemId.value) {
      loadEnergyData();
    }
  });
});

// 当前选择的时间维度和数据类型
const currentTimeScope = ref<"day" | "week" | "month" | "year">("day");
const currentDataType = ref<"data" | "analysis">("data");

// 处理日期变更事件
const handleDateChange = (dateInfo: { type: string; date: Date }) => {
  // 如果正在加载，直接返回
  if (energyLoading.value) return;

  // 重置数据
  resetData();

  const obj: any = {
    day: 0,
    week: 2,
    month: 3,
    year: 4
  };

  const type = obj[dateInfo.type];
  timeType.value = type;
  currentTimeScope.value = dateInfo.type as "day" | "week" | "month" | "year";

  // 根据类型设置日期范围，参考 onChangeType 逻辑
  switch (type) {
    case 0: // day
      const today = dayjs(dateInfo.date);
      setDates(today, today, 0);
      break;
    case 2: // week
      const weekStart = dayjs(dateInfo.date).startOf("week").add(0, "day");
      const weekEnd = dayjs(dateInfo.date).endOf("week").add(0, "day");
      setDates(weekStart, weekEnd, 1);
      break;
    case 3: // month
      const monthStart = dayjs(dateInfo.date).startOf("month");
      const monthEnd = dayjs(dateInfo.date).endOf("month");
      setDates(monthStart, monthEnd, 1);
      break;
    case 4: // year
      const yearStart = dayjs(dateInfo.date).startOf("year");
      const yearEnd = dayjs(dateInfo.date).endOf("year");
      setDates(yearStart, yearEnd, 3);
      break;
  }

  // 加载数据
  loadEnergyData();
};

const formatDate = (date: any) => {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

// 设置日期范围，参考 greentree_h5 中的 setDates 逻辑
const setDates = (start: any, end: any, type: number) => {
  if (!queryData.value) {
    queryData.value = {
      hemsId: 1229,
      beginDate: "",
      endDate: "",
      type: 0,
      zone: "Asia/Shanghai"
    };
  }

  queryData.value.type = type;
  queryData.value.beginDate = start.format("YYYY-MM-DD");
  queryData.value.endDate = end.format("YYYY-MM-DD");

  // 更新 currentSelectTime 用于兼容现有逻辑
  currentSelectTime = queryData.value.beginDate;
};
// 处理标签变更事件
const handleTabChange = (tab: string) => {
  console.log("标签变更:", tab);
  currentDataType.value = tab as "data" | "analysis";
};

// 监听processedData变化，通知子组件更新图表
// watch(
//   [processedData, energyTotals],
//   (newVal, oldVal) => {
//     console.log("父组件监听到数据变化:", {
//       solarListLength: processedData.value.solarList?.length,
//       timePointsLength: processedData.value.timePoints?.length,
//       energyTotals: energyTotals.value.solarTotal
//     });

//     if (processedData.value.solarList && processedData.value.solarList.length > 0) {
//       nextTick(() => {
//         console.log("通知子组件更新图表");
//         // 通知所有子组件更新图表
//         solarRef.value?.updateCharts();
//         homeRef.value?.updateCharts();
//         batteryRef.value?.updateCharts();
//       });
//     }
//   },
//   { deep: true, immediate: true }
// );
// 调用能源接口
const loadEnergyData = async () => {
  if (!systemId.value || energyLoading.value) return;

  energyLoading.value = true;
  try {
    // 如果 queryData 还没有初始化，使用默认值
    if (!queryData.value) {
      queryData.value = {
        hemsId: 1229,
        beginDate: currentSelectTime || formatDate(new Date()),
        endDate: currentSelectTime || formatDate(new Date()),
        type: timeType.value,
        zone: "Asia/Shanghai"
      };
    }

    const params = queryData.value;

    // 调用hook中的数据获取方法
    await getSolarFlowData(params, 0, timeType.value); // currentSelect = 0 表示获取所有PV数据
    await getGridData(params, timeType.value);
    // 如果需要电池SOC数据，也获取一下
    if (timeType.value === 0) {
      // 只有实时模式才需要SOC数据
      await getBatteryData(params, timeType.value);
    }

    console.log("能源数据加载完成:", {
      energyTotals: energyTotals.value,
      processedData: processedData.value,
      solarListLength: processedData.value.solarList?.length,
      timePointsLength: processedData.value.timePoints?.length
    });
  } catch (error) {
    console.error("加载能源数据失败:", error);
  } finally {
    energyLoading.value = false;
  }
};
</script>
